<template>
  <view class="tools-container">
    <!-- 工具分类 -->
    <view class="tools-grid">
      <!-- 健康监测 -->
      <view class="tool-card card" @click="openHealthMonitor">
        <view class="tool-icon">🏠</view>
        <view class="tool-content">
          <text class="tool-name">健康监测</text>
          <text class="tool-desc">实时监测身体恢复状况</text>
        </view>
        <view class="tool-arrow">▶</view>
      </view>

      <!-- 节省计算器 -->
      <view class="tool-card card" @click="openSavingsCalculator">
        <view class="tool-icon">💰</view>
        <view class="tool-content">
          <text class="tool-name">节省计算器</text>
          <text class="tool-desc">计算戒烟节省的金钱</text>
        </view>
        <view class="tool-arrow">▶</view>
      </view>

      <!-- 渴求记录 -->
      <view class="tool-card card" @click="goToCravingHistory">
        <view class="tool-icon">📊</view>
        <view class="tool-content">
          <text class="tool-name">渴求记录</text>
          <text class="tool-desc">记录和分析吸烟冲动</text>
        </view>
        <view class="tool-arrow">▶</view>
      </view>

      <!-- 呼吸训练 -->
      <view class="tool-card card" @click="openBreathingExercise">
        <view class="tool-icon">🌬️</view>
        <view class="tool-content">
          <text class="tool-name">呼吸训练</text>
          <text class="tool-desc">缓解压力的呼吸练习</text>
        </view>
        <view class="tool-arrow">▶</view>
      </view>

      <!-- 替代活动 -->
      <view class="tool-card card" @click="openAlternativeActivities">
        <view class="tool-icon">🎯</view>
        <view class="tool-content">
          <text class="tool-name">替代活动</text>
          <text class="tool-desc">健康的替代行为建议</text>
        </view>
        <view class="tool-arrow">▶</view>
      </view>

      <!-- 紧急求助 -->
      <view class="tool-card card emergency" @click="openEmergencyHelp">
        <view class="tool-icon">🆘</view>
        <view class="tool-content">
          <text class="tool-name">紧急求助</text>
          <text class="tool-desc">想吸烟时的紧急应对</text>
        </view>
        <view class="tool-arrow">▶</view>
      </view>
    </view>

    <!-- 模态框 -->
    <view class="modal" v-if="showModal" @click="closeModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">{{ modalTitle }}</text>
          <view class="close-btn" @click="closeModal">✕</view>
        </view>
        <view class="modal-body">
          <!-- 健康监测内容 -->
          <view v-if="modalType === 'health'" class="health-monitor">
            <view class="health-progress-list">
              <view class="progress-item" v-for="(item, index) in healthMetrics" :key="index">
                <view class="progress-header">
                  <text class="progress-name">{{ item.name }}</text>
                  <text class="progress-status" :class="item.status">{{ item.statusText }}</text>
                </view>
                <view class="progress-bar">
                  <view class="progress-fill" :style="{ width: item.progress + '%', backgroundColor: item.color }">
                  </view>
                </view>
                <text class="progress-desc">{{ item.description }}</text>
              </view>
            </view>
          </view>

          <!-- 节省计算器内容 -->
          <view v-if="modalType === 'savings'" class="savings-calculator">
            <view class="savings-stats">
              <view class="stat-box">
                <text class="stat-label">已节省金额</text>
                <text class="stat-value big">¥{{ savedMoney }}</text>
              </view>
              <view class="stat-row">
                <view class="stat-box">
                  <text class="stat-label">每日节省</text>
                  <text class="stat-value">¥{{ dailySavings }}</text>
                </view>
                <view class="stat-box">
                  <text class="stat-label">每月节省</text>
                  <text class="stat-value">¥{{ monthlySavings }}</text>
                </view>
              </view>
            </view>
          </view>

          <!-- 呼吸训练内容 -->
          <view v-if="modalType === 'breathing'" class="breathing-exercise">
            <view class="breathing-circle" :class="{ inhale: isInhaling, exhale: isExhaling }">
              <text class="breathing-text">{{ breathingText }}</text>
              <text class="breathing-count" v-if="isInhaling || isExhaling">{{ breathingCount }}</text>
            </view>
            <view class="breathing-controls">
              <button class="btn btn-primary" @click="startBreathing" v-if="!breathingActive">
                开始训练
              </button>
              <button class="btn btn-warning" @click="stopBreathing" v-else>
                停止训练
              </button>
            </view>
            <view class="breathing-stats">
              <text class="stats-text">已完成 {{ completedCycles }} 个呼吸周期</text>
            </view>
          </view>

          <!-- 替代活动内容 -->
          <view v-if="modalType === 'alternative'" class="alternative-activities">
            <view class="activity-list">
              <view class="activity-item" v-for="(activity, index) in currentActivities" :key="index">
                <view class="activity-icon">{{ activity.icon }}</view>
                <view class="activity-content">
                  <text class="activity-name">{{ activity.name }}</text>
                  <text class="activity-desc">{{ activity.description }}</text>
                  <text class="activity-time">⏱️ {{ activity.duration }}</text>
                </view>
              </view>
            </view>
          </view>

          <!-- 紧急求助内容 -->
          <view v-if="modalType === 'emergency'" class="emergency-help">
            <view class="emergency-message">
              <text class="message-title">想要吸烟是正常的！</text>
              <text class="message-text">这种感觉会过去的，让我们一起度过难关。</text>
            </view>
            <view class="emergency-actions">
              <button class="emergency-btn" @click="showMotivation">
                <text class="btn-icon">💪</text>
                <text class="btn-text">励志话语</text>
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useSmokingHistoryStore } from '@/store/smokingHistory'
import { storeToRefs } from 'pinia'

// 响应式数据
const showModal = ref<boolean>(false)
const modalType = ref<string>('')
const modalTitle = ref<string>('')
const smokingStore = useSmokingHistoryStore()
const { quitDate, dailyCigarettes, pricePerPack, cigarettesPerPack } = storeToRefs(smokingStore)

// 呼吸训练相关数据
const isInhaling = ref<boolean>(false)
const isExhaling = ref<boolean>(false)
const breathingActive = ref<boolean>(false)
const breathingText = ref<string>('准备开始')
const breathingCount = ref<number>(0)
const completedCycles = ref<number>(0)

// 计算属性
const quitDays = computed((): number => {
  if (!quitDate.value) return 0
  const quit = new Date(quitDate.value)
  const now = new Date()
  const diffTime = Math.abs(now.getTime() - quit.getTime())
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
})

const savedMoney = computed((): string => {
  if (!quitDate.value || quitDays.value === 0) return '0.00'
  const dailyCost = (dailyCigarettes.value / cigarettesPerPack.value) * pricePerPack.value
  return (dailyCost * quitDays.value).toFixed(2)
})

const dailySavings = computed((): string => {
  return ((dailyCigarettes.value / cigarettesPerPack.value) * pricePerPack.value).toFixed(2)
})

const monthlySavings = computed(() => {
  return (parseFloat(dailySavings.value) * 30).toFixed(2)
})

const healthMetrics = computed(() => [
  {
    name: '血液氧气',
    progress: Math.min(100, quitDays.value * 10),
    status: 'improving',
    statusText: '改善中',
    color: '#4facfe',
    description: '血液中氧气含量正在恢复正常'
  },
  {
    name: '肺功能',
    progress: Math.min(100, quitDays.value * 3),
    status: 'improving',
    statusText: '改善中',
    color: '#00f2fe',
    description: '肺部纤毛开始清理毒素'
  }
])

const currentActivities = [
  { icon: '🚶', name: '散步', description: '到户外走走，呼吸新鲜空气', duration: '10-15分钟' },
  { icon: '🏃', name: '慢跑', description: '轻松慢跑，释放内啡肽', duration: '20-30分钟' },
  { icon: '🎵', name: '听音乐', description: '播放喜欢的音乐放松心情', duration: '5-10分钟' },
  { icon: '📖', name: '阅读', description: '读几页喜欢的书籍', duration: '10-20分钟' }
]

// 打开工具弹窗
const openModal = (type: string, title: string) => {
  modalType.value = type
  modalTitle.value = title
  showModal.value = true
}

const openHealthMonitor = () => openModal('health', '健康监测')
const openSavingsCalculator = () => openModal('savings', '节省计算器')
const openBreathingExercise = () => openModal('breathing', '呼吸训练')
const openAlternativeActivities = () => openModal('alternative', '替代活动')
const openEmergencyHelp = () => openModal('emergency', '紧急求助')

// 关闭弹窗
const closeModal = () => {
  showModal.value = false
  if (breathingActive.value) {
    stopBreathing()
  }
}

const goToCravingHistory = () => {
  uni.navigateTo({
    url: '/pages/craving-history/craving-history'
  })
}

// 呼吸训练相关
let breathingTimer: ReturnType<typeof setTimeout> | null = null
let breathingInterval: ReturnType<typeof setInterval> | null = null
const startBreathing = () => {
  breathingActive.value = true
  completedCycles.value = 0
  startBreathingCycle()
}

const stopBreathing = () => {
  breathingActive.value = false
  if (breathingTimer) {
    clearTimeout(breathingTimer)
    breathingTimer = null
  }
  if (breathingInterval) {
    clearInterval(breathingInterval)
    breathingInterval = null
  }
  breathingText.value = '准备开始'
  breathingCount.value = 0
  isInhaling.value = false
  isExhaling.value = false
}

const startBreathingCycle = () => {
  // 吸气阶段
  breathingText.value = '吸气'
  isInhaling.value = true
  isExhaling.value = false

  let count = 4
  breathingCount.value = count

  breathingInterval = setInterval(() => {
    count--
    breathingCount.value = count
    if (count <= 0) {
      clearInterval(breathingInterval!)
      // 屏气阶段
      breathingText.value = '屏气'
      // isInhaling.value = false
      // isExhaling.value = true
      count = 7
      breathingCount.value = count

      breathingInterval = setInterval(() => {
        count--
        breathingCount.value = count
        if (count <= 0) {
          clearInterval(breathingInterval!)

          // 呼气阶段
          breathingText.value = '呼气'
          isInhaling.value = false
          isExhaling.value = true

          let count = 4
          breathingCount.value = count
          breathingInterval = setInterval(() => {
            count--
            breathingCount.value = count
            if (count <= 0) {
              clearInterval(breathingInterval!)
              isExhaling.value = false
              completedCycles.value++

              if (breathingActive.value) {
                breathingText.value = '准备吸气'
                breathingTimer = setTimeout(startBreathingCycle, 1000)
              }
            }
          }, 1000)
        }
      }, 1000)
    }
  }, 1000)
}

const showMotivation = () => {
  const motivations = [
    '你已经坚持了这么久，不要放弃！',
    '想想你戒烟的初衷和目标',
    '这种感觉很快就会过去的',
    '你比你想象的更强大',
    '喝口水，深呼吸，它就会过去。',
    '动起来！快走五分钟！​',
    '烟瘾只是个纸老虎，别怕！​',
    '不要被 yourself  hindering your progress.',
    '冲过去！5分钟后就赢了！​',
    '这是考验，冲过去就是英雄！​',
    '深呼吸三次，欲望会减弱。',
    '我不是烟的奴隶，我能做主！',
    '它强由它强，清风拂山岗。​',
    '习惯可以改变，你正在改变！​',
    '一口烟，所有的努力都白费！',
    '​刷会儿手机，转移注意力。',
    '烟瘾就像海浪，它涌上来，但一定会退去。你只需要稳稳地站住这几分钟。',
    '你对自己的承诺，比烟重要！​',
    '你每忍住一次，肺就干净一分。'
  ]
  const randomMotivation = motivations[Math.floor(Math.random() * motivations.length)]

  uni.showModal({
    title: '加油！',
    content: randomMotivation,
    showCancel: false,
    confirmText: '我能行！'
  })
}
</script>

<style lang="scss" scoped>
.tools-container {
  padding: 20rpx;
}

.tools-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20rpx;
}

.tool-card {
  display: flex;
  align-items: center;
  padding: 30rpx;
  transition: transform 0.3s ease;

  &:active {
    transform: scale(0.95);
  }

  &.emergency {
    background: linear-gradient(135deg, #ff6b6b 0%, #ffa726 100%);
    color: #fff;

    .tool-content {

      .tool-name,
      .tool-desc {
        color: #fff;
      }
    }

    .tool-arrow {
      color: #fff;
    }
  }

  .tool-icon {
    font-size: 48rpx;
    margin-right: 20rpx;
  }

  .tool-content {
    flex: 1;

    .tool-name {
      display: block;
      font-size: 30rpx;
      font-weight: 600;
      margin-bottom: 8rpx;
    }

    .tool-desc {
      font-size: 24rpx;
      color: #666;
    }
  }

  .tool-arrow {
    font-size: 24rpx;
    color: #667eea;
  }
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.modal-content {
  width: 600rpx;
  max-height: 80vh;
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .modal-title {
    font-size: 32rpx;
    font-weight: 600;
  }

  .close-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background: #f5f5f5;
    font-size: 24rpx;
  }
}

.modal-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

// 健康监测样式
.progress-item {
  margin-bottom: 40rpx;

  &:last-child {
    margin-bottom: 0;
  }

  .progress-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15rpx;

    .progress-name {
      font-size: 28rpx;
      font-weight: 500;
    }

    .progress-status {
      font-size: 22rpx;
      padding: 6rpx 12rpx;
      border-radius: 20rpx;
      background: #e8f5e8;
      color: #4caf50;
    }
  }

  .progress-bar {
    height: 12rpx;
    background: #f0f0f0;
    border-radius: 6rpx;
    overflow: hidden;
    margin-bottom: 10rpx;

    .progress-fill {
      height: 100%;
      border-radius: 6rpx;
      transition: width 0.3s ease;
    }
  }

  .progress-desc {
    font-size: 22rpx;
    color: #666;
  }
}

// 节省计算器样式
.savings-stats {
  .stat-box {
    text-align: center;
    margin-bottom: 30rpx;

    .stat-label {
      display: block;
      font-size: 24rpx;
      color: #666;
      margin-bottom: 10rpx;
    }

    .stat-value {
      display: block;
      font-size: 32rpx;
      font-weight: 600;
      color: #333;

      &.big {
        font-size: 48rpx;
        color: #4facfe;
      }
    }
  }

  .stat-row {
    display: flex;
    gap: 30rpx;
  }
}

// 渴求记录样式
.craving-form {
  .form-item {
    margin-bottom: 30rpx;

    .form-label {
      display: block;
      font-size: 26rpx;
      margin-bottom: 15rpx;
      font-weight: 500;
    }
  }
}

// 新增渴求记录样式
.quick-record {
  margin-bottom: 30rpx;
  
  .section-title {
    display: block;
    font-size: 28rpx;
    font-weight: 600;
    margin-bottom: 15rpx;
    color: #333;
  }
  
  .quick-buttons {
    display: flex;
    gap: 15rpx;
    
    .quick-btn {
      flex: 1;
      padding: 20rpx;
      border-radius: 12rpx;
      border: none;
      font-size: 24rpx;
      font-weight: 500;
      
      &.low {
        background: #e8f5e8;
        color: #4caf50;
      }
      
      &.medium {
        background: #fff3e0;
        color: #ff9800;
      }
      
      &.high {
        background: #ffebee;
        color: #f44336;
      }
    }
  }
}

.today-stats {
  margin-bottom: 30rpx;
  
  .stats-summary {
    display: flex;
    gap: 30rpx;
    
    .stat-item {
      text-align: center;
      
      .stat-number {
        display: block;
        font-size: 36rpx;
        font-weight: 600;
        color: #667eea;
        margin-bottom: 5rpx;
      }
      
      .stat-label {
        font-size: 22rpx;
        color: #666;
      }
    }
  }
}

.detailed-form {
  margin-bottom: 30rpx;
  
  .intensity-labels {
    display: flex;
    justify-content: space-between;
    margin-top: 10rpx;
    
    .intensity-label {
      font-size: 20rpx;
      color: #999;
    }
  }
  
  .triggers-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx;
    margin-top: 15rpx;
    
    .trigger-tag {
      padding: 12rpx 20rpx;
      border-radius: 20rpx;
      background: #f5f5f5;
      font-size: 22rpx;
      color: #666;
      border: 2rpx solid transparent;
      transition: all 0.3s ease;
      
      &.active {
        background: #667eea;
        color: #fff;
      }
      
      &.custom {
        background: #e3f2fd;
        color: #2196f3;
        border: 2rpx dashed #2196f3;
      }
    }
  }
  
  .custom-trigger-input {
    margin-top: 15rpx;
    
    .custom-input {
      width: 100%;
      padding: 15rpx;
      border: 2rpx solid #e0e0e0;
      border-radius: 8rpx;
      font-size: 24rpx;
      margin-bottom: 15rpx;
    }
    
    .input-actions {
      display: flex;
      gap: 15rpx;
      
      .btn-small {
        padding: 12rpx 20rpx;
        border-radius: 8rpx;
        font-size: 22rpx;
        border: none;
        
        &.btn-primary {
          background: #667eea;
          color: #fff;
        }
        
        &.btn-cancel {
          background: #f5f5f5;
          color: #666;
        }
      }
    }
  }
  
  .note-textarea {
    width: 100%;
    min-height: 120rpx;
    padding: 15rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 8rpx;
    font-size: 24rpx;
    resize: none;
  }
  
  .full-width {
    width: 100%;
    margin-top: 20rpx;
  }
}

.strategies {
  margin-bottom: 30rpx;
  
  .strategy-list {
    .strategy-item {
      display: flex;
      align-items: center;
      padding: 20rpx;
      background: #f8f9fa;
      border-radius: 12rpx;
      margin-bottom: 15rpx;
      
      .strategy-icon {
        font-size: 32rpx;
        margin-right: 15rpx;
      }
      
      .strategy-content {
        flex: 1;
        
        .strategy-title {
          display: block;
          font-size: 26rpx;
          font-weight: 500;
          margin-bottom: 5rpx;
        }
        
        .strategy-desc {
          font-size: 22rpx;
          color: #666;
        }
      }
    }
  }
}

.view-history {
  margin-top: 30rpx;
  text-align: center;
  
  .btn-outline {
    background: transparent;
    border: 2rpx solid #667eea;
    color: #667eea;
    padding: 20rpx 40rpx;
    border-radius: 25rpx;
    font-size: 24rpx;
    
    &:active {
      background: #667eea;
      color: #fff;
    }
  }
}

// 呼吸训练样式
.breathing-exercise {
  text-align: center;
}

.breathing-circle {
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0 auto 30rpx;
  &.inhale {
    transition: transform 4s linear;
    transform: scale(1.25);
  }

  &.exhale {
    transition: transform 4s linear;
    transform: scale(1);
  }

  .breathing-text {
    color: #fff;
    font-size: 28rpx;
    font-weight: 600;
    margin-bottom: 10rpx;
  }

  .breathing-count {
    color: #fff;
    font-size: 36rpx;
    font-weight: 600;
  }
}

.breathing-controls {
  margin-bottom: 30rpx;
}

.breathing-stats {
  .stats-text {
    font-size: 24rpx;
    color: #666;
  }
}

// 替代活动样式
.activity-list {
  .activity-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .activity-icon {
      font-size: 40rpx;
      margin-right: 20rpx;
    }

    .activity-content {
      flex: 1;

      .activity-name {
        display: block;
        font-size: 26rpx;
        font-weight: 600;
        margin-bottom: 8rpx;
      }

      .activity-desc {
        display: block;
        font-size: 22rpx;
        color: #666;
        margin-bottom: 6rpx;
      }

      .activity-time {
        font-size: 20rpx;
        color: #999;
      }
    }
  }
}

// 紧急求助样式
.emergency-help {
  text-align: center;
}

.emergency-message {
  margin-bottom: 30rpx;

  .message-title {
    display: block;
    font-size: 32rpx;
    font-weight: 600;
    margin-bottom: 15rpx;
    color: #ff6b6b;
  }

  .message-text {
    font-size: 26rpx;
    color: #666;
  }
}

.emergency-actions {
  display: grid;
  grid-template-columns: repeat(1, 1fr);

  .emergency-btn {
    display: flex;
    align-items: center;
    padding: 10rpx 20rpx;
    background: #f8f9fa;
    border-radius: 16rpx;
    border: none;

    .btn-icon {
      font-size: 30rpx;
      margin-right: 10rpx;
    }

    .btn-text {
      font-size: 22rpx;
      color: #333;
    }
  }
}
</style>